package com.oms.web.filter;

import java.io.IOException;
import java.net.URLDecoder;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;


import com.oms.domain.User;
import com.oms.service.AcknowledgementService;
import com.oms.service.UserService;


public class AutoLoginFilter implements Filter {
	
	@Resource
	UserService userServiceInter;
	
	@Resource
	AcknowledgementService acknowledgementService;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
//		HttpServletResponse resp = (HttpServletResponse) response;
		
		System.out.println("查看本次请求的用户是否已经登录");
		//查看用户是否已经登录，未登录才实现自动登录检验
		if(req.getSession(false)==null || req.getSession().getAttribute("user")==null){
			//2.读取Cookies信息
			Cookie [] cs = req.getCookies();
			Cookie findC = null;
			if(cs!=null){
				for(Cookie c : cs){
					if("autoLogin".equals(c.getName())){
						findC = c;
						break;
					}
				}
			}
			if(findC!=null){
				//当自动登录Cookie存在，开始自动登录
				System.out.println("本次请求的用户未登录，找到自动登录cookie");
				String v = URLDecoder.decode(findC.getValue(),"utf-8");
				String userEmail = v.split(":")[0];
				String password = v.split(":")[1];
				System.out.println("邮箱是："+userEmail + "； 密码是：" + password);
				User user=null;
				try{
					user=userServiceInter.loginByEmail(userEmail, password);
				}catch(RuntimeException e){
					System.out.println(e.getMessage());
				}
				if(user!=null){
					Integer unReadMsgNumber=acknowledgementService.getUnReadMsgCount(user);
					req.getSession().setAttribute("user", user);
					req.getSession().setAttribute("unReadMsgNumber", unReadMsgNumber);
					System.out.println(unReadMsgNumber);
					System.out.println("实现自动登录");
				}
			}
		}
				
		//返回过滤器链
		chain.doFilter(request, response);

	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
